package com.example.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.common.exception.CaptchaException;
import com.example.common.lang.Const;
import com.example.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码验证处理器
 */


@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtil redisUtil;            //调用RedisUtil工具类

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String url = request.getRequestURI();           //获取请求的URL

        if("/login".equals(url) && request.getMethod().equals("POST")) {    //如果URL是login的POST请求

            try {
                validate(request);          //调用下方validate方法，校验验证码
            }catch (CaptchaException e) {
                loginFailureHandler.onAuthenticationFailure(request,response,e);    //如果验证失败捕获异常调用登录失败处理器处理
            }
        }

        filterChain.doFilter(request,response);         //无异常则继续执行
    }


    private void validate(HttpServletRequest request) {              //校验验证码的逻辑

        String code = request.getParameter("code");           //从请求中获取code
        String key = request.getParameter("token");           //从请求中获取token

        if(StringUtils.isBlank(code) || StringUtils.isBlank(key)) {     //如果key或code为空直接返回异常
            throw new CaptchaException("验证码错误");
        }

        if(!code.equals(redisUtil.hget(Const.CAPTCHA_KEY,key))) {        //判断请求中的code与redis中的是否相同
            throw new CaptchaException("验证码错误");
        }

        redisUtil.hdel(Const.CAPTCHA_KEY,key);          //删除redis中的code，一次性使用

    }
}
